<template>
    <div id="add-edit-WaitRectify">
        <el-dialog
            title="登记整改结果"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="80px" :rules="rules">
                <el-row :gutter="35">
                    <el-divider content-position="left">基础数据</el-divider>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="整改结果">
                            <el-select 
                                class="m-2" 
                                placeholder="请选择整改结果" 
                                v-model="ruleForm.n_RectificationState"
                            >
                                <el-option
                                    v-for="item in resultOption"
                                    :key="item.id"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="整改时间" prop="d_RectificationTime">
                            <el-date-picker
                                v-model="ruleForm.d_RectificationTime"
                                type="date"
                                value-format="YYYY-MM-DD"
                                placeholder="请选择开始日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="整改措施" prop="v_Measures">
                            <el-input v-model="ruleForm.v_Measures" type="textarea" autosize placeholder="整改措施" clearable />
                            <!-- <el-select 
                                class="m-2" 
                                placeholder="请选择整改措施" 
                                v-model="ruleForm.v_Measures" 
                                multiple
                                collapse-tags
                            >
                                <el-option
                                    v-for="item in typeOption"
                                    :key="item.id"
                                    :label="item.value"
                                    :value="item.value"
                                />
                            </el-select> -->
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="复查部门" prop="v_ReviewDeptName">
                            <el-cascader 
                                v-model="ruleForm.l_ReviewDeptId"
                                :options="orgOption" 
                                :props="orgProps" 
                                @change="orgChange"
                                clearable 
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="复查人员" prop="v_ReviewUserName">
                            <el-select 
                                v-model="ruleForm.v_ReviewUserName" 
                                filterable 
                                :disabled="isForbidden"
                                :readonly="isForbidden"
                                class="m-2" 
                                :placeholder="chosePlaceholder" 
                                @change="useChange"
                                value-key="id"
                                popper-class="set-select"
                                :popper-append-to-body="false"
                            >
                                <el-option
                                    v-for="item in useOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-divider content-position="left">整改图片上传</el-divider>
                    <div style="padding: 0 20px;width: 100%;">
                        <FileView
                            ref="fileRef"
                            isAccept=".jpg,.jpeg,.png"
                            :fileInfo="fileInfo"
                            :componentKey="componentKey"
                        />
                    </div>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue';
import { 
    FormInstance, 
    FormRules, 
    ElButton, 
    ElCol, 
    ElDialog, 
    ElDivider, 
    ElForm, 
    ElFormItem, 
    ElOption, 
    ElRow, 
    ElSelect,
    ElMessage,
} from 'element-plus';
import { sysUserSelector , sysFileInfoMultipleUpload } from '/@/api/centerControl/pubilc';
import FileView from '../file-view.vue';
import { SMSHDRectifyRectificationResult } from '/@/api/centerControl/sms';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    id: Number, // 整改记录id
    n_RectificationState: Number, // 整改结果状态
    d_RectificationTime: String, // 整改时间
    v_Measures: String, // 整改措施
    l_ReviewDeptId: Number, // 复查部门id
    v_ReviewDeptName: String, // 复查部门名称
    l_ReviewUserId: Number, // 复查人员id
    v_ReviewUserName: String, // 复查人员名称
}
export default defineComponent( {
    name: 'add-edit-WaitRectify',
    components: {FileView},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        },
        bascObj: {
            type: Object,
            default: {},
        }
    },
    setup(props,ctx){
        const ruleFormRef = ref();
        const typeOption = ref();
        const orgOption = ref();
        const useOptions = ref();
        const fileRef = ref();
        const fileInfo = ref();
        const chosePlaceholder = ref('先选择部门');
        const isForbidden = ref(true);

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            d_RectificationTime: [
				{ required: true, message: '请选择整改时间', trigger: 'change' },
			],
            v_Measures: [
				{ required: true, message: '请选择整改措施', trigger: 'change' },
			],
            v_ReviewDeptName: [
				{ required: true, message: '请选择复查部门', trigger: 'change' },
			],
            v_ReviewUserName: [
				{ required: true, message: '请选择复查人员', trigger: 'change' },
			],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    state.repeatDis = true;
                    let item: any = state.ruleForm;
                    item.v_Measures = item.v_Measures.join("，");
                    fileFun(item);
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** 文件上传 */
        const fileFun = async(val: any) => {
            if(fileRef.value.fileList.length !== 0){
                let setArr:any = [];
                fileRef.value.fileList.map((i: any) => {
                    setArr.push(i.raw);
                });
                let res: any;
                let param: any = {};
                param.files = setArr;
                param.sourceId = JSON.parse(props.repairInfo).l_RectifyFileId;
                param.sourceType = 10;
                try{
                    res = await SMSHDRectifyRectificationResult(val);
                    if(res.success){
                        try{
                            let rcs: any = await sysFileInfoMultipleUpload(param);
                            if(rcs.success){
                                state.repeatDis = false;
                                ctx.emit('controlUseClick');
                                ctx.emit('updateData');
                            }else{
                                state.repeatDis = false;
                                ctx.emit('controlUseClick');
                            }
                        }catch(error){ state.repeatDis = false; }
                    }else{
                        state.repeatDis = false;
                    }
                }catch(error){ state.repeatDis = false; }
            }else{
                ElMessage({
                    type: 'warning',
                    message: '请上传整改图片',
                    duration: 1000,
                    onClose: () => {
                        state.repeatDis = false;
                    }
                })
            }
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        // 获取用户数据
        const useFun = async(id: number) => {
            let param: any = {};
            param.orgId = id;
            let res:any = await sysUserSelector(param)
            if(res.success){
                if(res.data.length !== 0){
                    useOptions.value = res.data;
                    chosePlaceholder.value = '请选择用户';
                    isForbidden.value = false;
                }else{
                    chosePlaceholder.value = '当前部门暂无用户';
                    isForbidden.value = true;
                }
                
            }
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                if(Object.keys(props.bascObj).length !== 0){
                    let treeData = JSON.parse(props.bascObj.treeData);
                    let typeData = JSON.parse(props.bascObj.typeData);
                    if(treeData !== '' && typeData !== ''){
                        console.log(treeData,'treeData');
                        console.log(typeData,'typeData')
                        orgOption.value = treeData;
                        typeOption.value = typeData;
                    }
                }
                chosePlaceholder.value = '先选择部门';
                isForbidden.value = true;
                let item = JSON.parse(props.repairInfo);
                fileInfo.value = JSON.stringify({sourceId: item.l_RectifyFileId});
                state.ruleForm = {
                    id: JSON.parse(props.repairInfo).id, // 整改记录id
                    n_RectificationState: 0, // 整改结果状态
                    d_RectificationTime: '', // 整改时间
                    v_Measures: '', // 整改措施
                    l_ReviewDeptId: 0, // 复查部门id
                    v_ReviewDeptName: '', // 复查部门名称
                    l_ReviewUserId: 0, // 复查人员id
                    v_ReviewUserName: '', // 复查人员名称
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        /*** 复查部门改变事件 */
        const orgChange = (val: any) => {
            console.log(val)
            let len = val.length - 1;
            if(val && val.length !== 0){
                state.ruleForm.l_ReviewDeptId = val[len];
                state.ruleForm.v_ReviewDeptName = val[len];
                state.ruleForm.l_ReviewUserId = 0; // 隐患排查人员id
                state.ruleForm.v_ReviewUserName = ''; // 隐患排查人员名称
                useFun(val[len]);
            }
        }

        /*** 复查人员改变事件 */
        const useChange = (val: any) => {
            state.ruleForm.l_ReviewUserId = val;
        }

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            ...toRefs(state),
            isUseDialog,
            resultOption: [
                {id: 0, label: '已消除', value: 0},
                {id: 1, label: '未消除', value: 1}
            ],
            rules,
            typeOption,
            chosePlaceholder,
            isForbidden,
            orgProps: { checkStrictly: true , label: 'title', value: 'id', children: 'children' },
            orgOption,
            orgChange,
            useOptions,
            useChange,
            componentKey: 1,
            fileInfo,
            fileRef,
        }
    },
} )
</script>
<style scoped lang="scss">
#file-view{
    width: 100%;
}
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
</style>